<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="所属银行" prop="tableName">
        <el-select v-model="queryParams.tableName" placeholder="请选择所属银行" clearable>
          <el-option label="蓝海银行" value="ecs_pay_ease" />
          <el-option label="蓝海/苏商/厦门" value="ecs_yee_pay" />
          <el-option label="苏商/华通" value="ecs_baofu_merchant" />
          <el-option label="银联代扣" value="ecs_yee_pay_withholding" />
          <el-option label="绑卡代扣" value="ecs_yeepay_withhold" />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺名称" prop="signedShorthand">
        <el-input v-model="queryParams.signedShorthand" placeholder="请输入店铺名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属平台" v-if="user.userId === 1" prop="platformNickName">
        <el-input v-model="queryParams.platformNickName" placeholder="请输入所属平台" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属代理" v-if="user.deptId < 101" prop="agentNickName">
        <el-input v-model="queryParams.agentNickName" placeholder="请输入所属代理" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属二级代理" v-if="user.deptId < 102" prop="childAgentNickName">
        <el-input v-model="queryParams.childAgentNickName" placeholder="请输入所属二级代理" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商户昵称" v-if="user.deptId < 102" prop="shopNickName">
        <el-input v-model="queryParams.shopNickName" placeholder="请输入商户昵称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="最小余额" prop="balance">
        <el-input-number v-model="queryParams.balance" placeholder="请输入最小余额" :step="10"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-top-right" size="mini"
          @click="isAll = true; cashTitle = '全部提现'; cashOpen = true"
          v-hasPermi="['ecs:withdrawal:withdrawalAll']">全部提现</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="separateAccountsList">
      <el-table-column label="所属银行" align="center" prop="tableName" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.tableName === 'ecs_pay_ease'">蓝海银行</span>
          <span v-else-if="scope.row.tableName === 'ecs_yee_pay'">蓝海/苏商/厦门</span>
          <span v-else-if="scope.row.tableName === 'ecs_din_pay'">智付锡商</span>
          <span v-else-if="scope.row.tableName === 'ecs_baofu_merchant'">苏商/华通</span>
          <span v-else-if="scope.row.tableName === 'ecs_yee_pay_withholding'">银联代扣</span>
          <span v-else-if="scope.row.tableName === 'ecs_yeepay_withhold'">绑卡代扣</span>
        </template>
      </el-table-column>
      <el-table-column label="账户余额" v-if="user.userId === 1" align="center" min-width="100">
        <template slot-scope="{row}">
          {{ Math.round((row.platformBalance + row.agentBalance + row.childAgentBalance + row.shopBalance) * 100) / 100 }}
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" show-overflow-tooltip align="center" prop="signedShorthand" min-width="300">
        <template slot-scope="{ row }">
          {{ row.signedShorthand }}
        </template>
      </el-table-column>
      <el-table-column label="公司名称" show-overflow-tooltip align="center" prop="name" min-width="150">
        <template slot-scope="{ row }">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column label="所属平台" show-overflow-tooltip v-if="user.userId === 1" align="center"
        prop="platformNickName" min-width="150">
        <template slot-scope="{ row }">
          {{ row.platformNickName }}
        </template>
      </el-table-column>
      <el-table-column label="所属代理" show-overflow-tooltip v-if="user.deptId < 101" align="center" prop="agentNickName"
        min-width="150">
        <template slot-scope="{ row }">
          {{ row.agentNickName }}
        </template>
      </el-table-column>
      <el-table-column label="所属二级代理" show-overflow-tooltip v-if="user.deptId < 102" align="center"
        prop="childAgentNickName" min-width="150">
        <template slot-scope="{ row }">
          {{ row.childAgentNickName }}
        </template>
      </el-table-column>
      <el-table-column :label="user.userId === 1 ? '平台余额' : '余额'" v-if="user.userId === 1 || user.deptId === 100"
        align="center" prop="platformBalance" min-width="100">
        <template slot-scope="{ row }">
          {{ row.platformBalance }}
        </template>
      </el-table-column>
      <el-table-column :label="user.userId === 1 ? '代理余额' : '余额'" v-if="user.userId === 1 || user.deptId === 101"
        align="center" prop="agentBalance" min-width="100">
        <template slot-scope="{ row }">
          {{ row.agentBalance }}
        </template>
      </el-table-column>
      <el-table-column :label="user.userId === 1 ? '二级代理余额' : '余额'" v-if="user.userId === 1 || user.deptId === 102"
        align="center" prop="childAgentBalance" min-width="100">
        <template slot-scope="{ row }">
          {{ row.childAgentBalance }}
        </template>
      </el-table-column>
      <el-table-column :label="user.userId === 1 ? '店铺余额' : '余额'" v-if="user.userId === 1 || user.deptId === 200"
        align="center" prop="shopBalance" min-width="100">
        <template slot-scope="{ row }">
          {{ row.shopBalance }}
        </template>
      </el-table-column>
      <el-table-column label="自动提现" align="center" v-if="user.deptId === 200 || user.userId === 1"
        prop="isAutomaticWithdrawal" min-width="100">
        <template slot-scope="{ row }">
          <el-switch v-model="row.isAutomaticWithdrawal" :active-value="1" :inactive-value="0"
            :disabled="automaticDisabled === row.id" @change="handleAutomaticChange(row)"></el-switch>
        </template>
      </el-table-column>

      <template v-if="user.userId !== 1">
        <el-table-column label="收款方姓名" show-overflow-tooltip align="center" min-width="100">
          <template slot-scope="{ row }">
            {{ row.accountName }}
          </template>
        </el-table-column>
        <el-table-column label="提现银行" align="center" prop="bankName" min-width="120">
          <template slot-scope="{ row }">
            {{ row.bankName }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text"
              @click="isAll = false; form = scope.row; cashTitle = '对 ' + scope.row.signedShorthand + ' 提现'; cashOpen = true"
              v-hasPermi="['ecs:withdrawal:withdrawal']">提现</el-button>
            <el-button size="mini" type="text" @click="setWithdrawalAccount(scope.row)">配置提现账户</el-button>
          </template>
        </el-table-column>
      </template>

    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="cashTitle" :visible.sync="cashOpen"
      width="500px" append-to-body>
      <el-form size="small" :inline="true" label-width="80px">
        <el-form-item label="手机号">
          <el-col :span="16">
            <el-input v-model="user.phonenumber" placeholder="请输入手机号" disabled />
          </el-col>
          <el-col :span="8">
            <el-link @click="href" :underline="false" type="primary">立即配置</el-link>
          </el-col>
        </el-form-item>
        <el-form-item label="验证码">
          <el-col :span="16">
            <el-input v-model="smsCode" placeholder="请输入短信验证码" />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" style="width: 100%;" plain :disabled="sendingSms" @click="sendSms">{{ sendSmsText
            }}</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="备注">
          <el-input :maxlength="64" v-model="queryParams.remark" placeholder="请输入备注 " />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="balaLoading" @click="submitCash" v-clickOnce>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="配置提现账户"
      :visible.sync="withdrawalAccountOpen" width="500px" append-to-body>
      <el-select filterable v-model="form.withdrawalAccountId" placeholder="请选择提现账户" clearable style="width: 240px">
        <el-option v-for="item in withdrawalAccountData" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="balaLoading" @click="submitCashWithdrawalAccount" v-clickOnce>确
          定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listShopIncoming, updateShopIncoming } from '@/api/ecs/shopIncoming'
import { withdrawalAll, withdrawal, updateWithdrawalAutomatic } from '@/api/ecs/withdrawal'
import { createCode, verifyCode } from '@/api/ecs/sms'
import { getUserProfile } from '@/api/system/user'
import { listWithdrawalAccount } from '@/api/ecs/withdrawalAccount'
import { getAgentUserId } from '@/api/ecs/agent'

export default {
  name: "Withdrawal",
  data() {
    return {
      // 遮罩层
      loading: true,
      balaLoading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      isAll: false,
      cashOpen: false,
      withdrawalAccountOpen: false,
      sendSmsText: "发送短信",
      cashTitle: "一键提现短信验证",
      separateAccountsList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: 9,
        tableName: null,
        signedShorthand: "",
        shopNickName: "",
        childAgentNickName: "",
        agentNickName: "",
        platformNickName: "",
      },
      productList: [],
      smsCode: '',
      sendingSms: false,
      user: {},
      form: {},
      automaticDisabled: 0,
      withdrawalAccountData: [],
    };
  },
  created() {
    getUserProfile().then(response => {
      this.user = response.data;
      if (this.user.deptId === 101) {
        getAgentUserId(this.user.userId).then(response => {
          if (response.data.agentId !== 0) {
            this.user.deptId = 102
          }
        });
      }
    });
    this.getList();
  },
  methods: {
    /** 查询所有三方入金后分账记录列表 */
    getList() {
      this.loading = true;
      listShopIncoming(this.queryParams).then(response => {
        this.separateAccountsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    href() {
      this.$router.push('/user/profile')
    },
    submitCash() {
      // if (this.user.userId === 402){
      //   this.$modal.msgError("暂时无法提现，请联系客服");
      //   return;
      // }
      if (!this.smsCode) {
        this.$modal.msgError("请填写短信验证码");
      } else {
        this.balaLoading = true
        verifyCode({
          code: this.smsCode
        }).then(res => {
          if (res.data === true) {
            if (this.isAll) {
              this.handleWithdrawalAll()
            } else {
              this.handleWithdrawal()
            }
          } else {
            // this.handleWithdrawal()
            this.balaLoading = false
            this.$modal.msgError("无效的短信验证码");
          }
        }).catch(() => {
          // this.handleWithdrawal()
          this.balaLoading = false
        })
      }
    },
    sendSms() {
      createCode({}).then(response => {
        if (response.code === 200) {
          this.sendingSms = true;
          let countSec = 60
          let intervalId = setInterval(() => {
            countSec--;
            this.sendSmsText = countSec + "秒后可重发";
            if (countSec <= 0) {
              clearInterval(intervalId);
              this.sendingSms = false;
              this.sendSmsText = "发送`短信";

            }
          }, 1000)
        }
      })
    },
    setWithdrawalAccount(row) {
      this.form = { ...row }
      this.withdrawalAccountOpen = true
      listWithdrawalAccount({ tableName: row.tableName }).then(res => {
        this.withdrawalAccountData = res.rows
      })
    },
    submitCashWithdrawalAccount() {
      if (!!this.form.withdrawalAccountId) {
        updateShopIncoming({
          id: this.form.id,
          version: this.form.version,
          withdrawalAccountId: this.form.withdrawalAccountId,
        }).then(res => {
          if (res.code === 200) {
            this.withdrawalAccountOpen = false
            this.getList();
          }
        })
      }
    },
    /** 导出按钮操作 */
    handleWithdrawalAll() {
      withdrawalAll(this.queryParams).then(res => {
        this.smsCode = ""
        this.balaLoading = false
        if (res.code === 200) {
          if (res.data === true) {
            this.cashOpen = false
            this.$modal.msgSuccess("提现中.......");
          }
        }
      }).catch(() => {
        this.balaLoading = false
      })
    },
    handleWithdrawal() {
      withdrawal({ requestId: this.form.requestId }).then(res => {
        this.smsCode = ""
        this.balaLoading = false
        if (res.code === 200) {
          if (res.data === true) {
            this.cashOpen = false
            this.$modal.msgSuccess("提现中.......");
          }
        }
      }).catch(() => {
        this.balaLoading = false
      })
    },
    handleAutomaticChange(row) {
      this.automaticDisabled = row.id
      updateWithdrawalAutomatic({ id: row.id, isAutomaticWithdrawal: row.isAutomaticWithdrawal, version: row.version }).then(res => {
        this.automaticDisabled = 0
        this.getList()
      }).catch(() => {
        row.isAutomaticWithdrawal = row.isAutomaticWithdrawal === 1 ? 0 : 1
        this.automaticDisabled = 0
      })
      // let text = row.status === "0" ? "启用" : "停用";
      // this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
      //   // return changeUserStatus(row.userId, row.status);
      // }).then(() => {
      //   this.$modal.msgSuccess(text + "成功");
      // }).catch(function() {
      //   row.status = row.status === "0" ? "1" : "0";
      // });
    },
  }
};
</script>
